package com.dhms.vostok1.ui.main.mine

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.dhms.uikit.DialogBuilder
import com.dhms.basebusiness.R
import com.dhms.vostok1.data.BaseListItem
import com.dhms.vostok1.databinding.FragmentSettingBinding
import com.dhms.vostok1.model.SettingViewModel
import com.dhms.vostok1.service.net.NetworkApi
import com.dhms.vostok1.ui.main.MainActivity

class SettingFragment : Fragment() {

    private var _binding: FragmentSettingBinding? = null
    private val binding get() = _binding!!

    private val settingViewModel: SettingViewModel by activityViewModels()

    private lateinit var serverAddressInputDialog: AlertDialog

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = viewLifecycleOwner

        setToolbar()

        setOptionList()

        initServerAddressInputDialog()
    }

    private fun setToolbar() {
        binding.topAppBar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        val exitDevModelDialog =
            DialogBuilder(requireContext()).setTitle(getString(R.string.setting_exit_dev_mode_tip))
                .setOnPositiveButtonClickListener {
                    settingViewModel.writeSettings(
                        mapOf(
                            "DEV_MODE" to false
                        )
                    )
                    findNavController().navigateUp()
                    true
                }.setOnNegativeButtonClickListener().createDialog()

        binding.topAppBar.setOnMenuItemClickListener {
            if (it.itemId == com.dhms.vostok1.R.id.menu_exit_dev_node) {
                exitDevModelDialog.show()
                return@setOnMenuItemClickListener true
            }
            false
        }
    }

    private fun initServerAddressInputDialog() {
        val currentBaseUrl = settingViewModel.settingMap.value!!["BASE_URL"] as String
        val currentWebViewBaseUrl =
            settingViewModel.settingMap.value!!["BASE_URL"] as String
        var inputServerAddress = ""
        serverAddressInputDialog =
            DialogBuilder(requireContext()).setTitle(getString(R.string.setting_server_address_hint))
                .setOnPositiveButtonClickListener {
                    NetworkApi.initNetwork(inputServerAddress)

                    settingViewModel.writeSettings(
                        mapOf(
                            "BASE_URL" to inputServerAddress
                        )
                    )

                    binding.settingServerAddressWrapper.itemValue.text = inputServerAddress
                    Log.i(TAG, "The base url has been changed to $inputServerAddress.")

                    if (activity is MainActivity) {
                        Toast.makeText(requireContext(), "设置成功，请重新登录！", Toast.LENGTH_SHORT).show()
//                        (activity as MainActivity).logout()
                    } else {
                        Toast.makeText(requireContext(), "设置成功！", Toast.LENGTH_SHORT).show()
                    }

                    true
                }.setOnNegativeButtonClickListener()
                .setEditable(currentBaseUrl, rules = listOf(IP_REGEX, DOMAIN_REGEX)) {
                    inputServerAddress = it.toString()
                }.createDialog()
    }


    private fun setOptionList() {
        binding.settingServerAddressWrapper.baseListItemWrapper.setOnClickListener {
            serverAddressInputDialog.show()
        }
        binding.settingServerAddressWrapper.item =
            BaseListItem(
                itemTitle = getString(R.string.setting_server_address),
                itemSuffixIcon = ResourcesCompat.getDrawable(
                    resources,
                    com.dhms.vostok1.R.drawable.ic_arrow_right,
                    null
                ),
                itemValue = settingViewModel.settingMap.value!!["BASE_URL"] as String
            )
    }

    companion object {
        const val TAG = "SettingFragment"
        val IP_REGEX =
            """^http(s?)://((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)(:\d+)?$""".toRegex(
                RegexOption.IGNORE_CASE
            )
        val DOMAIN_REGEX =
            """^http(s?)://((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}(:\d+)?$""".toRegex(
                RegexOption.IGNORE_CASE
            )
    }
}
